import logging
import os
from pathlib import Path

from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.staticfiles import StaticFiles

from dc_shop.config import load_config
from dc_shop.core.constants import IMAGES_FOLDER
from dc_shop.core.logger import configure_logging
from dc_shop.webapp.app.controllers import setup_controllers
from dc_shop.webapp.app.providers.main import setup_providers

logger = logging.getLogger(__name__)


def init_app() -> FastAPI:
    config = load_config()
    configure_logging()

    app = FastAPI()
    app.mount(
        "/static",
        StaticFiles(directory=os.path.join(Path(__file__).parent, "static")),
        name="static",
    )
    app.mount("/images", StaticFiles(directory=IMAGES_FOLDER), name="images")

    origins = [
        "https://highgrowingthailand.click/",
        "http://highgrowingthailand.click/",
        "http://localhost",
        "http://localhost:5005",
    ]
    app.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    setup_providers(app, config)
    setup_controllers(app)

    logger.info("API initialized")

    return app
